import { Injectable } from '@angular/core';
import { CmHttp } from "http-module";
import { Observable } from "rxjs/Observable";
import { SummaryWithTrading, SUMMARY_STATUS } from "./summary";
import { BASEURL, STOCKURL } from "shared";
import * as moment from "moment";

export const STOCK_STATUS = {
  NORMAL: 0,
  OCALL: 1,
  STOP_AND_TRADING_DAY: 2
};

export const getStockStatus =
  (summary: SummaryWithTrading, isTrade: boolean) =>
    isTrade && summary ? // 是否交易日
      summary.status === SUMMARY_STATUS.SUSP || summary.status === SUMMARY_STATUS.STOPT ? // 交易日停牌
        STOCK_STATUS.STOP_AND_TRADING_DAY :
        summary.status === SUMMARY_STATUS.OCALL || summary.status === SUMMARY_STATUS.START ? // 交易日非停牌，是否集合竞价？
          STOCK_STATUS.OCALL : // 交易日非停牌，集合竞价阶段
          STOCK_STATUS.NORMAL : // 交易日非停牌，非集合竞价阶段，状态正常
      STOCK_STATUS.NORMAL; // 非交易日，正常

@Injectable()
export class SummaryAssistantService {

  constructor(private http: CmHttp) {

  }
  getSummaryBySymbol(symbol: string, date = moment().format("YYYY-MM-DD")): Observable<SummaryWithTrading> {
    let { http } = this;
    return Observable.zip(
      http.get(`${STOCKURL}/api/v2/sc/charts/${symbol}/summary`, {}, {cacheAge: http.CACHE_AGE.Instant}),
      Observable.of({ date: date, isTrading: true }),  // http.get(`${BASEURL}/stock/tradingdate?date=${date}`),
      (summary, isTrade) => {
        let summary = summary && summary.data ? summary.data : {}
        return Object.assign({}, summary, {
          tradeDayToJudge: isTrade.date,
          isTrading: isTrade.isTrading,
          stockStatus: getStockStatus(summary, isTrade.isTrading)
        }
      })
    );
  }
}